package com.im.partchat.ui.activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.im.partchat.R;
import com.im.partchat.base.BaseActivity;
import com.im.partchat.bean.Department;
import com.im.partchat.db.dao.DeptDao;
import com.im.partchat.utils.rxlifecycle.compact.RxLifecycleCompact;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.rong.imkit.plugin.location.AMapLocationInfo;
import io.rong.imkit.plugin.location.IMyLocationChangedListener;
import io.rong.imkit.plugin.location.LocationManager;

public class LocationActivity extends BaseActivity implements IMyLocationChangedListener, LocationSource, AMap.OnMarkerClickListener {

    @BindView(R.id.mapView)
    MapView mAMapView;
    @BindView(R.id.tv_part_name)
    TextView tvPartName;
    @BindView(R.id.tv_part_address)
    TextView tvPartAddress;
    @BindView(R.id.tv_part_create_time)
    TextView tvPartCreateTime;
    @BindView(R.id.tv_part_part_number)
    TextView tvPartPartNumber;
    @BindView(R.id.tv_part_part_phone)
    TextView tvPartPartPhone;
    @BindView(R.id.ll_location_info)
    LinearLayout llLocationInfo;
    @BindView(R.id.rc_ext_my_location)
    ImageView rcExtMyLocation;
    private AMap mAMap;
    private Marker mMarker;
    private BitmapDescriptor mBitmapDescriptor;
    private Handler mHandler;
    private LocationSource.OnLocationChangedListener mLocationChangedListener;
    private double mMyLat;
    private double mMyLng;
    private String mMyPoi;
    private double mLatResult;
    private double mLngResult;
    private String mPoiResult;

    private List<Department> departmentList;

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        this.mAMapView.onCreate(savedInstanceState);
        this.mHandler = new Handler();
        LocationManager.getInstance().bindConversation(getApplicationContext(), null, null);
        this.initMap();
        this.initLocation();

    }

    private void initLocation() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(io.rong.imkit.R.drawable.rc_ext_my_locator));
        myLocationStyle.strokeWidth(0.0F);
        myLocationStyle.strokeColor(io.rong.imkit.R.color.rc_main_theme);
        myLocationStyle.radiusFillColor(0);
        mAMap.setMyLocationStyle(myLocationStyle);

        LocationManager.getInstance().setMyLocationChangedListener(this);

    }

    private void initMap() {
        mAMap = mAMapView.getMap();
        mAMap.setLocationSource(this);
        mAMap.setMyLocationEnabled(true);
        mAMap.getUiSettings().setZoomControlsEnabled(false);
        mAMap.getUiSettings().setMyLocationButtonEnabled(false);
        mAMap.setMapType(1);
        mAMap.setOnMarkerClickListener(this);


    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_location;
    }

    @Override
    protected void initData() {


        Observable.create(new ObservableOnSubscribe<List<Department>>() {
            @Override
            public void subscribe(ObservableEmitter<List<Department>> e) throws Exception {
                List<Department> allDepart = DeptDao.getInstance().getAllDepart();
                e.onNext(allDepart);
                e.onComplete();
            }
        })
                .compose(RxLifecycleCompact.bind(LocationActivity.this).<List<Department>>withObservable())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<List<Department>>() {
                    @Override
                    public void accept(List<Department> departmentList) throws Exception {
                        onLoadDataSuccess(departmentList, null);
                    }
                });
    }

    @Override
    public void onLoadDataSuccess(Object o, String flag) {

        departmentList = (List<Department>) o;

        for (Department department : departmentList) {
            if (TextUtils.isEmpty(department.getJd())
                    || TextUtils.isEmpty(department.getWd())
                    || TextUtils.isEmpty(department.getAddress())) {
                continue;
            }
            this.mBitmapDescriptor = BitmapDescriptorFactory.fromBitmap(getMyBitmap(department.getName()));
            MarkerOptions markerOptions = (new MarkerOptions())
                    .anchor(0.5F, 0.5F)
                    .position(new LatLng(Double.valueOf(department.getWd()), Double.valueOf(department.getJd())))
                    .icon(this.mBitmapDescriptor)
                    .draggable(false);

            Marker marker = mAMap.addMarker(markerOptions);
            marker.setObject(department);
        }

    }

    protected void onDestroy() {
        this.mAMapView.onDestroy();
        LocationManager.getInstance().setMyLocationChangedListener(null);
        mAMap = null;
        super.onDestroy();
    }

    @Override
    public void onMyLocationChanged(final AMapLocationInfo locationInfo) {
        if (this.mLocationChangedListener != null) {
            this.mHandler.post(new Runnable() {
                public void run() {
                    if (locationInfo != null) {
                        mMyLat = mLatResult = locationInfo.getLat();
                        mMyLng = mLngResult = locationInfo.getLng();
                        mMyPoi = mPoiResult = locationInfo.getStreet() + locationInfo.getPoiname();
                        Location location = new Location("AMap");
                        location.setLatitude(locationInfo.getLat());
                        location.setLongitude(locationInfo.getLng());
                        location.setTime(locationInfo.getTime());
                        location.setAccuracy(locationInfo.getAccuracy());
                        mLocationChangedListener.onLocationChanged(location);
                        addMyLocatedMarker(new LatLng(mLatResult, mLngResult), mPoiResult);


                    } else {
                        showToast("获取个人位置失败");
                    }

                }
            });
        }
    }

    @OnClick(R.id.rc_ext_my_location)
    public void onViewClicked() {
        if (mMyPoi != null) {

            mMarker.setPosition(new LatLng(mMyLat, mMyLng));
            mAMap.moveCamera(CameraUpdateFactory.newCameraPosition((new CameraPosition.Builder())
                    .target(new LatLng(mMyLat, mMyLng))
                    .zoom(14.0F)
                    .bearing(0.0F)
                    .tilt(30.0F)
                    .build()));
            mLatResult = mMyLat;
            mLngResult = mMyLng;
            mPoiResult = mMyPoi;
        } else {
            LocationManager.getInstance().updateMyLocation();
        }
    }

    private void addMyLocatedMarker(LatLng latLng, String poi) {
        this.mBitmapDescriptor = BitmapDescriptorFactory.fromBitmap(getMyBitmap("（我的位置）"));
        MarkerOptions markerOptions = (new MarkerOptions())
                .anchor(0.5F, 0.5F)
                .position(latLng)
                .icon(this.mBitmapDescriptor)
                .draggable(false);

        this.mMarker = this.mAMap.addMarker(markerOptions);
        mMarker.setPosition(latLng);
        mAMap.moveCamera(CameraUpdateFactory.newCameraPosition((new CameraPosition.Builder())
                .target(new LatLng(latLng.latitude, latLng.longitude))
                .zoom(14.0F)
                .bearing(0.0F)
                .tilt(30.0F)
                .build()));

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        this.mLocationChangedListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        Department department = (Department) marker.getObject();
        if (department != null) {
            llLocationInfo.setVisibility(View.VISIBLE);
            updateInfoBar(department);
        } else {
            llLocationInfo.setVisibility(View.GONE);
        }
        return false;
    }

    public void updateInfoBar(Department department) {
        tvPartName.setText(department.getName());
        tvPartAddress.setText("地址：" + department.getAddress());
        tvPartCreateTime.setText("成立时间：" + department.getClsj());
        tvPartPartNumber.setText("发展党员：共" + department.getNumber() + "名");
        tvPartPartPhone.setText("联系电话：" + department.getTel());
    }

    protected Bitmap getMyBitmap(String pm_val) {
        Bitmap bitmap = BitmapDescriptorFactory.fromResource(
                R.drawable.rc_ext_location_marker).getBitmap();
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        bitmap = Bitmap.createBitmap(bitmap, 0 ,0, width, height);
        Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        bitmap.recycle();
        Canvas canvas = new Canvas(mutableBitmap);
        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(30f);
        textPaint.setColor(getResources().getColor(R.color.colorPrimary));
        textPaint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText(pm_val, width/2, 35 ,textPaint);
        return mutableBitmap;
    }
}
